package com.cah.project.module.meta.config;

import cn.hutool.core.util.StrUtil;
import com.cah.project.exception.BusinessException;
import com.cah.project.module.meta.config.query.DbQueryRegistry;
import com.cah.project.module.meta.config.query.IDbQuery;
import com.cah.project.module.meta.domain.entity.DataSourceEntity;
import com.cah.project.module.meta.domain.vo.DataSourceInfo;
import com.cah.project.module.meta.enums.DbTypeEnum;
import lombok.Data;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 功能描述: 数据库配置 <br/>
 */
@Data
public class DataSourceConfig {

    /** 数据库实例 */
    private String schemaName;
    /** 驱动连接的url */
    private String url;
    /** 驱动名称 */
    private String driverName;
    /** 数据库连接用户名 */
    private String username;
    /** 数据库连接密码 */
    private String password;
    /** 数据库类型 */
    private DbTypeEnum dbType;
    /** 数据库查询语句 */
    private IDbQuery dbQuery;

    public DataSourceConfig(DataSourceInfo info) {
        this.dbType = DbTypeEnum.indexOf(info.getType());
        this.username = info.getUsername();
        this.password = info.getPassword();
        this.schemaName = StrUtil.isEmpty(info.getServiceName()) ? this.username : info.getServiceName();
        this.driverName = info.getDriverClassName();
        this.dbQuery = DbQueryRegistry.getDbQuery(this.dbType);
        this.url = this.dbQuery.getUrl(info.getHost(), info.getPort(), this.schemaName) + info.getOtherParam();
    }

    public DataSourceConfig(DataSourceEntity entity) {
        this.dbType = DbTypeEnum.indexOf(entity.getType());
        this.username = entity.getUsername();
        this.password = entity.getPassword();
        this.schemaName = StrUtil.isEmpty(entity.getServiceName()) ? this.username : entity.getServiceName();
        this.driverName = entity.getDriverClassName();
        this.dbQuery = DbQueryRegistry.getDbQuery(this.dbType);
        this.url = this.dbQuery.getUrl(entity.getHost(), entity.getPort(), this.schemaName) + entity.getOtherParam();
    }

    public Connection getConn() {
        Connection conn;
        try {
            Class.forName(this.driverName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException | SQLException e) {
            throw new BusinessException(e.getMessage());
        }
        return conn;
    }

}
